今天我們會把風扇組裝起來,並且在上面執行一套完整的 具紅外線遙控功能的 電風扇。
由於紅外線接收模組需要拉到外面來,所以我們找到一個帶紅外線遙控接收 的四節 7 段顯示器,此顯示器模組詳細的控制功能,您可以參考這篇:从零开始打造基于MicroPython的电子时钟(3)
由於此顯示目前的驅動程式採用 I2C 方式,但在選擇過高的 I2C clock 會造成顯示不穩定,因此我們選擇在 10K。
我們以第四種馬達爲例來組裝,此馬達拉出五條電線:
控制小板的接線:
上邊綠色端子排:
下邊藍色端子排:
測試接線如下:
整合好的控制程式如下:
from machine import Timer, Pin, I2C
import FourDigitDisplay as FDD
import time
from micropython import const
from ir_rx.nec import NEC_8 # NEC remote, 8 bit addresses
IR = Pin(2, Pin.IN)
buzz = Pin(12, Pin.OUT, value=0)
speed_ctl = Pin(13, Pin.OUT)
swing = Pin(15, Pin.OUT, value=0)
# IR code
ADDR = const(0)
PWR_ON = const(0x43)
SPD_UP = const(0x47)
SPD_DN = const(0x45)
SWING = const(0x46)
TMR_UP = const(0x15)
TMR_DN = const(0x7)
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=10000)
fdd = FDD.FourDigitDisplay(i2c)
i2c.scan()
fdd.clear()
ir_code_old = 0
ir_code_new = 0
speed = 0 # Hz
fan_on = False
swing_on = False
t0 = Timer(-1) # software timer
def toogle_speed(t):
speed_ctl.value(not speed_ctl.value())
def change_speed(speed):
global t0
global fdd
t0.init(freq=speed*2*50, mode=Timer.PERIODIC, callback=toogle_speed)
fdd.showbit(int(speed),3)
def beep():
buzz.value(1)
time.sleep_ms(100)
buzz.value(0)
def ir_cb(data, addr, ctrl):
global ir_code_new
global ir_code_old
global ADDR
if data < 0: # NEC protocol sends repeat codes.
print('Repeat code.')
else:
print('Data {:02x} Addr {:04x}'.format(data, addr))
if (addr == ADDR):
ir_code_new = data
ir_code_old = 0
ir = NEC_8(IR, ir_cb)
# power on beep()
beep()
beep()
beep()
beep()
while True:
#time.sleep_ms(1)
if (ir_code_new == ir_code_old):
continue
print('Cheking...')
beep()
ir_code_old = ir_code_new
if (ir_code_new == PWR_ON):
if (fan_on == True):
speed = 0
fan_on = False
swing_on = False
swing.value(swing_on)
change_speed(speed)
fdd.clear()
beep()
time.sleep_ms(200)
beep()
print('Off')
else:
fan_on = True
speed = 1
change_speed(speed)
print('On')
continue
if (fan_on == True):
if (ir_code_new == SPD_UP): # increase speed
speed += 1
if (speed > 8): speed = 8
change_speed(speed)
elif (ir_code_new == SPD_DN): #decrease speed
speed -= 1
if (speed < 0): speed = 0
change_speed(speed)
elif (ir_code_new == SWING): #swing
swing_on = not swing_on
swing.value(swing_on)
print('Done...')
測試完成之後,組裝風扇,就可以開始使用了!